﻿//---------------------------------------------------------------------------------
// Copyright 2011 Microsoft Corporation
// Licensed under the Microsoft Public License (MS-PL) (the "License"); 
// You may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.opensource.org/licenses/ms-pl.html
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR 
// CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, 
// INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR 
// CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 
// MERCHANTABLITY OR NON-INFRINGEMENT. 
// See the Microsoft Public License (MS-PL) for the specific language governing 
// permissions and limitations under the License.
//---------------------------------------------------------------------------------

using Microsoft.Telco.Controls.WindowsLive;
using ControlTestApplications.Silverlight.Dashboard.GatewayService;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;

namespace ControlTestApplications.Silverlight.Dashboard
{
    public partial class LiveSample : Page 
    {

        #region Private Fields
        private TimeSpan presenceRetrievalSpan = new TimeSpan(0, 0, 20);
        private System.Windows.Threading.DispatcherTimer updatePresenceTimer;
        string errorMessage;

        #endregion

        #region Constructore

        public LiveSample()
        {
            InitializeComponent();
            updatePresenceTimer = new System.Windows.Threading.DispatcherTimer();
            updatePresenceTimer.Tick += new EventHandler(updatePresenceTimer_Tick);
            updatePresenceTimer.Interval = presenceRetrievalSpan;
            Loaded += (s, e) =>
            {
                GetContacts();
            };
        }

        void updatePresenceTimer_Tick(object sender, EventArgs e)
        {
            GetContacts();
        }

        #endregion

        #region Overridable methods
        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        #endregion

        #region Methods

        private void GetContacts()
        {
            updatePresenceTimer.Stop();
            GatewayServiceClient client = new GatewayServiceClient();
            client.GetContactsCompleted += (s, e) =>
            {
                if (!HasError(e))
                {
                    contactsControl.Contacts = TransformResult(e.Result);
                    updatePresenceTimer.Start();
                }
                else
                {
                    if (!(e.Error is FaultException<AuthenticationFault>))
                    {
                        MessageBox.Show("Error getting contacts: " + errorMessage);
                    }
                }
                
            };
            client.GetContactsAsync();
        }

        private ObservableCollection<WLCategoryContacts> TransformResult(ObservableCollection<LiveContact> coll)
        {
            var contacts = new ObservableCollection<WLCategoryContacts>();
            WLCategoryContacts category = new WLCategoryContacts();
            category.CategoryName = string.Empty;
            category.CategoryContacts = new ObservableCollection<WLPresenceInfo>();
            foreach (var item in coll)
            {
                category.CategoryContacts.Add(new WLPresenceInfo
                {
                    DisplayText = item.Name,
                    PresenceStatus = GetStatusFromPresenceStatus(item.PresenceStatus)
                });
                //presenceControl.UserNameOrEmail = item.Name;
                //presenceControl.UserStatus = GetStatusFromPresenceStatus(item.PresenceStatus);
            }
            contacts.Add(category);
            return contacts;
        }

        private Status GetStatusFromPresenceStatus(LivePresenceStatus cs)
        {
            Status status = Status.Unknown;
            switch (cs)
            {
                case LivePresenceStatus.Online:
                    status = Status.Available;
                    break;
                case LivePresenceStatus.Busy:
                    status = Status.Busy;
                    break;
                case LivePresenceStatus.Away:
                    status = Status.Away;
                    break;
                case LivePresenceStatus.Offline:
                    status = Status.Offline;
                    break;
                case LivePresenceStatus.Unknown:
                    status = Status.Unknown;
                    break;
            }
            return status;
        }
        
        private bool HasError(AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (e.Error is FaultException<AuthenticationFault>)
                {
                    //Authentication required
                    var fault = e.Error as FaultException<AuthenticationFault>;
                    ChildWindow authWin = new AuthPrompt(fault.Detail.ConsentUrl);
                    authWin.Closed += new EventHandler(authWin_Closed);
                    authWin.Show();
                    errorMessage = null;
                    return true;
                }
                else if (e.Error is FaultException<TelcoFault>)
                {
                    var fault = e.Error as FaultException<TelcoFault>;
                    errorMessage = fault.Detail.Message;
                }
                else
                {
                    errorMessage = e.Error.Message;
                }
                return true;
            }
            return false;
        }

        void authWin_Closed(object sender, EventArgs e)
        {
            GetContacts();
        }
      
        #endregion
    }
}